package com.group1.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.group1.realtime.app.BaseAppV2;
import com.group1.realtime.bean.UserActionBean;
import com.group1.realtime.util.AtguiguUtil;
import com.group1.realtime.util.FlinkSinkUtil;
import org.apache.commons.collections.IteratorUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.group1.realtime.common.Constant.*;

public class Dws_UserActionAnalysis extends BaseAppV2 {

    public static void main(String[] args) {
        new Dws_UserActionAnalysis().init(
                3021,
                2,
                "Dws_UserActionAnalysis",
                TOPIC_DWD_TRAFFIC_PAGE,
                TOPIC_DWD_TRADE_ORDER_DETAIL,
                TOPIC_DWD_TRADE_CART_ADD,
                TOPIC_DWD_TRADE_PAYMENT_SUC
        );
    }


    @Override
    protected void handle(StreamExecutionEnvironment env, HashMap<String, DataStreamSource<String>> stream) {
        //处理浏览事务
        SingleOutputStreamOperator<UserActionBean> visitPageStream = processPageData(stream);
        //处理加购事务
        SingleOutputStreamOperator<UserActionBean> cartAddStream = processCartAdd(stream);
        //处理支付成功事务
        SingleOutputStreamOperator<UserActionBean> paymentSucStream = processPaymentSuc(stream);
        //处理下单事务
        SingleOutputStreamOperator<UserActionBean> orderedStream = processOrdered(stream);
        //合并流
        DataStream<UserActionBean> unionStream = visitPageStream.union(cartAddStream, paymentSucStream, orderedStream);
        //unionStream.print();
        //开窗聚合
        SingleOutputStreamOperator<UserActionBean> aggregatedStream = windowAndAgg(unionStream);
        aggregatedStream.print();
        writeToClickHouse(aggregatedStream);
    }



    private void writeToClickHouse(SingleOutputStreamOperator<UserActionBean> aggregatedStream) {
        aggregatedStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_action_analysis_window", UserActionBean.class));
    }

    private SingleOutputStreamOperator<UserActionBean> windowAndAgg(DataStream<UserActionBean> stream) {

        return stream.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<UserActionBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((bean, ts) -> bean.getTs())
                        .withIdleness(Duration.ofSeconds(5))
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .sideOutputLateData(new OutputTag<UserActionBean>("late"){})
                .reduce(
                        new ReduceFunction<UserActionBean>() {
                            @Override
                            public UserActionBean reduce(UserActionBean value1, UserActionBean value2) throws Exception {
                                value1.setVisitCourseCt(value1.getVisitCourseCt() + value2.getVisitCourseCt());
                                value1.setVisitHomeCt(value1.getVisitHomeCt() + value2.getVisitHomeCt());
                                value1.setCartAddCt(value1.getCartAddCt() + value2.getCartAddCt());
                                value1.setOrderedCt(value1.getOrderedCt() + value2.getOrderedCt());
                                value1.setPaymentSucCt(value1.getPaymentSucCt() + value2.getPaymentSucCt());
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<UserActionBean, UserActionBean, TimeWindow>() {
                            @Override
                            public void process(Context context, Iterable<UserActionBean> elements, Collector<UserActionBean> collector) throws Exception {

                                UserActionBean bean = elements.iterator().next();
                                bean.setStt(AtguiguUtil.toDateTime(context.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(context.window().getEnd()));

                                bean.setTs(System.currentTimeMillis());  // 把ts更新为聚合时间

                                collector.collect(bean);

                            }
                        }
                );


    }

    private SingleOutputStreamOperator<UserActionBean> processOrdered(Map<String, DataStreamSource<String>> stream) {

        return stream.get(TOPIC_DWD_TRADE_ORDER_DETAIL)
                .map(JSON::parseObject)
                .keyBy(object -> object.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, UserActionBean>() {

                    private ValueState<String> uidState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        uidState = getRuntimeContext().getState(new ValueStateDescriptor<String>("uidListState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject object, Context context, Collector<UserActionBean> collector) throws Exception {
                        long ordered = 0L;
                        Long ts = object.getLong("od_ts");
                        if (uidState.value() == null){
                            uidState.update(object.getString("user_id"));
                            ordered = 1L;
                            collector.collect(new UserActionBean(
                                    "", "", 0L, 0L,
                                    0L, ordered, 0L, ts));
                        }
                    }
                });

    }

    private SingleOutputStreamOperator<UserActionBean> processPaymentSuc(Map<String, DataStreamSource<String>> stream) {

        return stream.get(TOPIC_DWD_TRADE_PAYMENT_SUC)
                .map(JSON::parseObject)
                .keyBy(object -> object.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, UserActionBean>() {

                    private ValueState<String> uidState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        uidState = getRuntimeContext().getState(new ValueStateDescriptor<String>("uidListState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject object, Context context, Collector<UserActionBean> collector) throws Exception {
                        long paymentSuc = 0L;
                        Long ts = object.getLong("ts");
                        if (uidState.value() == null){
                            uidState.update(object.getString("user_id"));
                            paymentSuc = 1L;
                            collector.collect(new UserActionBean(
                                    "", "", 0L, 0L,
                                    0L, 0L, paymentSuc, ts));
                        }
                    }
                });
    }

    private SingleOutputStreamOperator<UserActionBean> processCartAdd(Map<String, DataStreamSource<String>> stream) {

        return stream.get(TOPIC_DWD_TRADE_CART_ADD)
                .map(JSON::parseObject)
                .keyBy(object -> object.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, UserActionBean>() {

                    private ValueState<String> uidState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        uidState = getRuntimeContext().getState(new ValueStateDescriptor<String>("uidListState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject object, Context context, Collector<UserActionBean> collector) throws Exception {
                        long cartAdd = 0L;
                        Long ts = object.getLong("ts");
                        if (uidState.value() == null){
                            uidState.update(object.getString("user_id"));
                            cartAdd = 1L;
                            collector.collect(new UserActionBean(
                                    "", "", 0L, 0L,
                                    cartAdd, 0L, 0L, ts));
                        }
                    }
                });

    }

    private SingleOutputStreamOperator<UserActionBean> processPageData(Map<String, DataStreamSource<String>> stream) {

        return stream.get(TOPIC_DWD_TRAFFIC_PAGE)
                .map(JSON::parseObject)
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject object) throws Exception {
                        JSONObject page = object.getJSONObject("page");
                        return "home".equals(page.getString("page_id"))
                                || "course_detail".equals(page.getString("page_id"));
                    }
                })
                .keyBy(object -> object.getJSONObject("page").getString("page_id"))
                .process(new KeyedProcessFunction<String, JSONObject, UserActionBean>() {


                    private List<String> uidList;
                    private ListState<String> uidState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        uidState = getRuntimeContext().getListState(new ListStateDescriptor<String>("uidListState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject object, Context context, Collector<UserActionBean> collector) throws Exception {

                        JSONObject common = object.getJSONObject("common");
                        JSONObject page = object.getJSONObject("page");
                        Long ts = object.getLong("ts");
                        long visitHome = 0L;
                        long visitCourse = 0L;
                        uidList = IteratorUtils.toList(uidState.get().iterator());
                        if (uidList.size() == 0 || !uidList.contains(common.getString("uid"))) {
                            uidState.add(common.getString("uid"));

                            if ("home".equals(page.getString("page_id"))) {
                                visitHome = 1L;
                            } else {
                                visitCourse = 1L;
                            }

                            collector.collect(new UserActionBean(
                                    "", "", visitHome, visitCourse,
                                    0L, 0L, 0L, ts));
                        }
                    }
                });


    }
}
